﻿/******
 * Begin in June 22th,2016.  By Shawn
 * 
 * This script is for using face++ through Web to get the face info.
 * The face is contained in a Texture2d which is captured by webCam or from an img and then converted to 
 * .Png format by the function tx.EncodeToJPG () . Then the img byte[] will be sent to facePP server
 * to get the info containing gender, race, age...e,g. * 
 * 
 * 
 * Attention: 
 * We need ConvertFacepassStrToClass.cs FaceStat and ReadFileTool.cs to analyse JSON
 * 
 * ********/




using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Net;


public class FacePPMgr : MonoBehaviour {

	private string api_key = "6246af9f4479ddb860860331972547a1";
	private string api_secret = "Fao4hhs-M6N34MYLIV_F-LOFm8c2wljm";	
	
	private string url = "http://apicn.faceplusplus.com/v2/detection/detect?";

	string resultTxt=string.Empty;

	public bool enablePost=true;



	FaceStat[] facStats;
	public FaceStat[] FacStats {
		get {
			return facStats;
		}
	}


	public IEnumerator PostImage (byte[] imgBytes)
	{
		enablePost=false;
		WWWForm form = new WWWForm ();
		form.AddField ("api_key", api_key);
		form.AddField ("api_secret", api_secret);
		form.AddBinaryData ("img", imgBytes, "temp.jpg", "image/jpg");
		form.AddField ("attribute", "glass,pose,gender,age,race,smiling");
		WWW www = new WWW (url, form);
		yield return www;
		
		resultTxt=www.text;
		//Debug.Log (www.text);
		enablePost=true;
		//Pay attention , we need to use  "ConvertFacepassStrToClass.FacepassStringToClasses" to desynchororize  JSOn  to filter anything outside square brackets.
		if(www.text.IndexOf("[")>=0)
		{
			facStats= ConvertFacepassStrToClass.FacepassStringToClasses<FaceStat>(www.text);
			if(facStats!=null)
			{
				if(facStats.Length>0)
					foreach(FaceStat mFcStat in  facStats  )
						if(mFcStat.attribute!=null)
					{
						Debug.Log ("FaceStat:  "+"age: "+ mFcStat.attribute.age.range.ToString()+"range:  "+  mFcStat.attribute.age.value.ToString());
					}
				
			}
		}
	}















}
